define(function(require, exports){
  'use strict';
  var $ = require('seajs/jquery.min');
  require('seajs/plugs/jquery.md5')($); 
  var _const = require('seajs/fn/fnConst');

  var getToken = function(_body, _key){
  	if(!_body && !_key){
  	  console.log('========== getToken 参数错误 ==========');
  	  return;
  	}
  	var arr = [];
  	var tmp = '';
  	for(var key in _body){
  	  arr.push(key);
  	}
  	arr.sort();
  	for(var i = 0; i < arr.length; i++){
  	  tmp += _body[arr[i]];
  	}
  	tmp += _key;
    _body['token'] = $.md5(tmp.toUpperCase());

  	return _body;
  }

  var getTCPPwd = function(_body, _key){
    if(!_body && !_key){
      console.log('========== getTCPPwd 参数错误 ==========');
      return;
    }
    var _pwd = _body['pwd'];
    delete _body['pwd'];
    var arr = [];
    var tmp = '';
    for(var key in _body){
      arr.push(key);
    }
    arr.sort();
    for(var i = 0; i < arr.length; i++){
      tmp = tmp + arr[i] + '=' + _body[arr[i]] + '&';
    }
    tmp += _pwd; 
    tmp += _key; 
    
    _body['pwd'] = $.md5(tmp);
    return _body;
  }

  /**********************************
  ************ date() ***************
  ***********************************/
  var getUnixTime = function(){
    return new Date().getTime();
  }

  //获取日期相关的两位数
  var formatDate = function(month){
    if(parseInt(month) < 10){
      return '0' + month;
    }
    return month;
  }

  //'2015-06-03 13:20:10'
  var getCurrentTime = function(){
    var now = new Date();
    return now.getFullYear() 
      + '-' + formatDate(now.getMonth() + 1) 
      + '-' + formatDate(now.getDate()) 
      + ' ' + formatDate(now.getHours()) 
      + ':' + formatDate(now.getMinutes()) 
      + ':' + formatDate(now.getSeconds());
  }

  var unixTimeFormat = function(unixTime){
    var formatNum = function(num){
      if(num < 10){
        num = '0' + num;
      }
      return num;
    }
    var time = new Date(unixTime);
    var y = formatNum(time.getFullYear());
    var m = formatNum(time.getMonth() + 1);
    var d = formatNum(time.getDate());
    var h = formatNum(time.getHours());
    var mm = formatNum(time.getMinutes());
    var s = formatNum(time.getSeconds());
    return y + '/' + m + '/' + d + ' ' + h + ':' + mm;
    //return y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s;
  }

  var contentFormat = function(content, topNum, bottomNum){
    if(content && !isNaN(topNum) && !isNaN(bottomNum)){
      var _length = content.length;
      if(topNum < 0){
        topNum = 0;
      }
      if(bottomNum < 0){
        bottomNum = 0;
      }
      var top = '', bottom = '';
      if(_length > topNum + bottomNum){
        if(topNum > 0){
          top = content.substring(0, topNum);
        }
        if(bottomNum > 0){
          bottom = content.substring(_length - bottomNum);
        }
        content = top + '*' + bottom;
      }
    }
    return content;
  }

  var formatDouble = function(num, right){
    // 判断当前数据是否数字
    if(isNaN(num)){
      return -1;
    }
    // 判断是否包含小数点
    var numstr = num.toString();
    if(numstr.indexOf('.') == -1){
      return numstr;
    }else{
      // 若小数点位数不大于传入值，则直接返回，否则截取传入位数
      if(numstr.split('.')[1].length <= right){
        return numstr;
      }
    }
    return parseFloat(num).toFixed(right);
  }

  var commonPost = function(path, data ,success, error){
    var _data = getToken(data, _const.FN_KEY);

    $.ajax({  
      type:'POST',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + path,
      data: _data,
      dataType:'json',
      success: function(rlt){
        success(rlt);
      },
      error: function(e){
        error(e);
      }
    });
  }

  var groupMemberLocationsQuery = function(uid, cmpid, key, success, error){
    var _data = getToken({
    'userid': uid,
    'timestamp': getUnixTime(),
    'userType': _const.DEVICE.DISPATCHER,
    'companyid': cmpid,
    'key': key
    }, _const.FN_KEY);

    $.ajax({  
      type:'POST',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + 'app/groupMemberLocationsQuery.do',
      data: _data,
      dataType:'json',
      success: function(data){
        success(data);
      },
      error: function(e){
        console.log(e);
        error(e);
      }
    });
  }

  var logout = function(uid, cmpid, key, success, error){
    var _data = getToken({
      'userid': uid,
      'timestamp': getUnixTime(),
      'userType': _const.DEVICE.DISPATCHER,
      'companyid': cmpid,
      'key': key
    }, _const.FN_KEY);

    $.ajax({  
      type:'POST',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + 'app/logout.do',
      data: _data,
      dataType:'json',
      success:function(data){
        success(data);
      },
      error: function(e){
        error(e);
      }
    });
  }

  var getAddGroupInfo = function(uid, cmpid, key, gid, success, error){
    var _data = getToken({
      'userid': uid,
      'timestamp': getUnixTime(),
      'userType': _const.DEVICE.DISPATCHER,
      'companyid': cmpid,
      'key': key,
      'groupid': gid
    }, _const.FN_KEY);

    $.ajax({  
      type:'GET',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + 'app/groupMemberQueryLoop.do?' 
        + 'userid=' + _data['userid'] + '&'
        + 'userType=' + _data['userType'] + '&'
        + 'companyid=' + _data['companyid'] + '&'
        + 'key=' + _data['key'] + '&'
        + 'groupid=' + _data['groupid'] + '&'
        + 'timestamp=' + _data['timestamp'] + '&'
        + 'token=' + _data['token'],
      dataType:'json',
      success:function(data){
        success(data);
      },
      error: function(e){
        error(e);
      }
    });
  }

  var getAddMemberInfo = function(uid, cmpid, key, _uid, success, error){
    var _data = getToken({
      'userid': uid,
      'timestamp': getUnixTime(),
      'userType': _const.DEVICE.DISPATCHER,
      'companyid': cmpid,
      'key': key,
      'uid': _uid
    }, _const.FN_KEY);

    $.ajax({  
      type:'GET',
      url:'http://' 
        + _const.HTTP.CONFIG.HOST + ':' 
        + _const.HTTP.CONFIG.PORT + '/' 
        + _const.HTTP.CONFIG.PATH + 'app/userQueryWithLocation.do?' 
        + 'userid=' + _data['userid'] + '&'
        + 'userType=' + _data['userType'] + '&'
        + 'companyid=' + _data['companyid'] + '&'
        + 'key=' + _data['key'] + '&'
        + 'uid=' + _data['uid'] + '&'
        + 'timestamp=' + _data['timestamp'] + '&'
        + 'token=' + _data['token'],
      dataType:'json',
      success:function(data){
        success(data);
      },
      error: function(e){
        error(e);
      }
    });
  }

  var exitDispatcher = function(ws){
    if(ws){
      if(ws.tasks.getCurrentId()){
        var task = ws.tasks.taskMap.get(ws.tasks.getCurrentId());

        switch(task.eventType){
          case _const.TASK_TYPE.SINGLE_CALL: //1
            ws.singleCallHangUp(task.cid, task.sid, ws.currentGid);
            break;
          case _const.TASK_TYPE.MEETTING: //2
            break;
          case _const.TASK_TYPE.TEMPORARY_GROUP: //3
            ws.exitGroup();
            ws.rtpWs.exitRtp();
            break;
          case _const.TASK_TYPE.BOARDCAST: //4
            ws.boardCastHangUp(task.cid, task.sid, ws.currentGid);
            break;
          default:
          //todo
        }
      }else{
        ws.exitGroup();
        ws.rtpWs.exitRtp();
      }
      ws.close();
    }
  }

  var goBackTalk = function(container, gid){
    container.tasks.remove(gid);
    $('#dialog').modal('hide');
    $('.main-bottom-middle > div').removeAttr('style');
    container.rtpWs.onMouseEvent();
    $('#ptt_status_img').attr('src', 'images/free.png');
    $('#ptt_status_span').html('空闲');
  }

  var memberSort = function(arr) {
　　if (arr.length <= 1) { return arr; }
　　var pivotIndex = Math.floor(arr.length / 2);
　　var pivot = arr.splice(pivotIndex, 1)[0];
　　var left = [];
　　var right = [];

　　for (var i = 0; i < arr.length; i++){
　　　　if (arr[i].py + '_' + arr[i].memberId < pivot.py + '_' + pivot.memberId) {
　　　　　　left.push(arr[i]);
　　　　} else {
　　　　　　right.push(arr[i]);
　　　　}
　　}
　　return memberSort(left).concat([pivot], memberSort(right));
  }

  var quickSort = function(arr){
    if (arr.length <= 1) { return arr; }
　　var pivotIndex = Math.floor(arr.length / 2);
　　var pivot = arr.splice(pivotIndex, 1)[0];
　　var left = [];
　　var right = [];

　　for (var i = 0; i < arr.length; i++){
　　　if (arr[i] < pivot) {
　　　　　left.push(arr[i]);
　　　} else {
　　　　　right.push(arr[i]);
　　　}
　　}
　　return memberSort(left).concat([pivot], memberSort(right));
  }

  var getQueryString = function(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
  }

  var saveLocal = function(key, value, expires){ // expires 单位：天
    if(window.localStorage){
      var curTime = new Date().getTime();
      window.localStorage.setItem(_const.LOCAL.FN_ + key, JSON.stringify({data:value, time:curTime, expires:expires}));
    }else{
      $.cookie(_const.LOCAL.FN_ + key, value, { expires: expires}); 
    }
  }

  var getLocal = function(key){
    var value = null;
    if(window.localStorage){
      var result = JSON.parse(window.localStorage.getItem(_const.LOCAL.FN_ + key));
      if(result !== null){
        if((new Date().getTime() - result.time)/1000/60/60/24 > JSON.parse(result.expires)) {
          delLocal(key);
        }else{
          value = result.data;
        }
      }
    }else{
      value = $.cookie(_const.LOCAL.FN_ + key);
    }
    return value;
  }

  var delLocal = function(key){
    if(window.localStorage){
      window.localStorage.removeItem(_const.LOCAL.FN_ + key);
    }else{
      $.cookie(_const.LOCAL.FN_ + key, '', { expires: - 1});
    }
  }

  var isPC = function(){
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) > 0) {
        flag = false;
        break;
      }
    }
    return flag;
  }

  exports.getToken = getToken,
  exports.getTCPPwd = getTCPPwd,
  exports.getUnixTime = getUnixTime,
  exports.formatDate = formatDate,
  exports.getCurrentTime = getCurrentTime,
  exports.unixTimeFormat = unixTimeFormat,
  exports.contentFormat = contentFormat,
  exports.formatDouble = formatDouble,
  exports.groupMemberLocationsQuery = groupMemberLocationsQuery,
  exports.logout = logout,
  exports.getAddGroupInfo = getAddGroupInfo,
  exports.getAddMemberInfo = getAddMemberInfo,
  exports.exitDispatcher = exitDispatcher,
  exports.goBackTalk = goBackTalk,
  exports.memberSort = memberSort,
  exports.quickSort = quickSort,
  exports.getQueryString = getQueryString,
  exports.saveLocal = saveLocal,
  exports.getLocal = getLocal,
  exports.delLocal = delLocal,
  exports.commonPost = commonPost,
  exports.isPC = isPC
  
});